﻿using MesGLApp.BLL.Mes;
using MesGLApp.DAL.Kingdee;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Vboot.App.K3CloudDataSend;
//using Gl_mes.DAL.MesDB;
//using Gl_mes.View;
//using Kingdee.BOS.WebApi.Client;
//using Microsoft.Office.Interop.Excel;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
//using NPOI.POIFS.FileSystem;
//using Sunny.UI;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text.Json.Nodes;
//using System.Threading.Tasks;
//using Vboot.App.K3CloudDataSend;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace MesGLApp.BLL.Mes
{
    public class KingdeeControler
    {
        //金蝶地址
        private string _url = "";
        //账套ID
        private string _db_id = "";
        //账号                     
        private string _user_name = "";
        //密码
        private string _pwd = "";
        //语言
        private int _language_id = 0;


        public KingdeeControler()
        {
            this._url = "http://192.168.5.108:8108/k3cloud/";       // "http://192.168.5.108:8108/k3cloud/";                 //本地："http://localhost/k3cloud/";
            this._db_id = "63b0535609eb4e";           //62e25e7bedd0a9 测试库账套ID    //63bd3b50d6fdf4  本地账套ID //63ddc9e8319821 230202 //63b0535609eb4e 正式  //64dcf18ff23422 IT专项测试_20230812
            this._user_name = "Administrator";
            this._pwd = "IT@2022";
            this._language_id = 2052;
        }


        /// <summary>
        /// 根据工单号查询工单的材料明细
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception> 
        public async Task<List<PrdPPBomDetail>> SearchPrdPPBomDetailByBillNo(string bill)
        {
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();
            List<PrdPPBomDetail> resList = new List<PrdPPBomDetail>();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

                List<object> Parameters = new List<object>();
                string condiStr = "fbillno='" + bill + "'";
                string cols = "fid,fbillno,FMaterialID2,FMaterialID2.fnumber,FMaterialID2.fname,FMaterialID2.FSPECIFICATION,FStdQty,FNeedQty2,FPickedQty";

                string counts = "{\"FormId\":\"PRD_PPBOM\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                    "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"\"," + "\"FieldKeys\":\"" + cols + "\"}";
                Parameters.Add(counts);
                httpClient.Content = JsonConvert.SerializeObject(Parameters);
                string results = httpClient.AsyncRequest();
                JArray jarr = JArray.Parse(results);

                int tmpInt = 0;
                decimal tmpDec = 0;
                if (jarr != null && jarr.Count() > 0)
                {
                    foreach (var item in jarr)
                    {
                        PrdPPBomDetail tmpBean = new PrdPPBomDetail();
                        tmpBean.parent_id = item[0] != null && int.TryParse(item[0].ToString().Trim(), out tmpInt) ? int.Parse(item[0].ToString().Trim()) : 0;
                        tmpBean.bill_no = item[1] != null ? item[1].ToString().Trim() : "";
                        tmpBean.mat_id = item[2] != null && int.TryParse(item[2].ToString().Trim(), out tmpInt) ? int.Parse(item[2].ToString().Trim()) : 0;
                        tmpBean.mat_info = new Material();
                        tmpBean.mat_info.mat_id = item[2] != null && int.TryParse(item[2].ToString().Trim(), out tmpInt) ? int.Parse(item[2].ToString().Trim()) : 0;
                        tmpBean.mat_info.mat_number = item[3] != null ? item[3].ToString().Trim() : "";
                        tmpBean.mat_info.mat_name = item[4] != null ? item[4].ToString().Trim() : "";
                        tmpBean.mat_info.mat_spe = item[5] != null ? item[5].ToString().Trim() : "";
                        tmpBean.std_qty = item[6] != null && decimal.TryParse(item[6].ToString().Trim(), out tmpDec) ? decimal.Parse(item[6].ToString().Trim()) : 0;
                        tmpBean.need_qty = item[7] != null && decimal.TryParse(item[7].ToString().Trim(), out tmpDec) ? decimal.Parse(item[7].ToString().Trim()) : 0;
                        tmpBean.fpi_qty = item[8] != null && decimal.TryParse(item[8].ToString().Trim(), out tmpDec) ? decimal.Parse(item[8].ToString().Trim()) : 0;
                        resList.Add(tmpBean);
                    }
                }

                return resList;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }
        }

        /// <summary>
        /// 根据工单号查询金蝶资料
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<PrdPPBom> SearchPrdPPBomByBillNo(string bill)
        {
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

                List<object> Parameters = new List<object>();
                string condiStr = "fbillno='" + bill + "'";
                string cols = "fid,fbillno,fmaterialid,fmaterialid.fnumber,fmaterialid.FOLDNUMBER,fmaterialid.fname,fmaterialid.fspecification,fqty," +
                                    "fmobillno,f_abc_text,f_abc_khdm,f_abc_base.fname,fcreatedate,fapprovedate,fmaterialid.flength,f_abc_remarks";

                string counts = "{\"FormId\":\"PRD_PPBOM\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                    "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"\"," + "\"FieldKeys\":\"" + cols + "\"}";
                Parameters.Add(counts);
                httpClient.Content = JsonConvert.SerializeObject(Parameters);
                string results = httpClient.AsyncRequest();
                JArray jarr = JArray.Parse(results);

                PrdPPBom tmpBean = new PrdPPBom();
                int tmpInt = 0;
                decimal tmpDec = 0;
                if (jarr != null && jarr.Count() > 0)
                {
                    var item = jarr[0];
                    tmpBean.id = item[0] != null && int.TryParse(item[0].ToString(), out tmpInt) ? int.Parse(item[0].ToString()) : 0;
                    tmpBean.bill_no = item[1] != null ? item[1].ToString() : "";
                    tmpBean.material_id = item[2] != null ? item[2].ToString() : "";
                    tmpBean.material_number = item[3] != null ? item[3].ToString() : "";
                    tmpBean.old_number = item[4] != null ? item[4].ToString() : "";
                    tmpBean.material_name = item[5] != null ? item[5].ToString() : "";
                    tmpBean.material_spe = item[6] != null ? item[6].ToString() : "";
                    tmpBean.qty = item[0] != null && decimal.TryParse(item[7].ToString(), out tmpDec) ? decimal.Parse(item[7].ToString()) : 0;
                    tmpBean.mo_bill_no = item[8] != null ? item[8].ToString() : "";
                    tmpBean.mto_no = item[9] != null ? item[9].ToString() : "";
                    tmpBean.client_number = item[10] != null ? item[10].ToString() : "";
                    tmpBean.saler_name = item[11] != null ? item[11].ToString() : "";
                    tmpBean.remark = item[15] != null ? item[15].ToString() : "";
                    tmpBean.create_date = item[12] != null ? item[12].ToString() : "";
                    tmpBean.material_length = item[14] != null ? item[14].ToString() : "";
                    tmpBean.approve_date = item[13] != null ? item[13].ToString() : "";
                }

                return tmpBean;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }

        }


        // <summary>
        /// 根据入库订单号查询生产订单号20240527z add
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<string> GetPRD_INSTOCK(string conStr)
        {
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
                List<object> list = new List<object>();
                var obj = new
                {
                    FormId = "PRD_INSTOCK",
                    FieldKeys = "FBillNo,FREALQTY,FMoBillNo,FCREATEDATE,FMtoNo",//入库单号,入库数量,生产订单号，日期,计划跟踪号
                    FilterString = conStr,
                    OrderString = "",
                    TopRowCount = 100,
                    StartRow = 0,
                    Limit = 0,
                    SubSystemId = ""
                };
                list.Add(obj);
                httpClient.Content = JsonConvert.SerializeObject(list);
                string results = httpClient.AsyncRequest();

                return results;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }

        }

        // <summary>
        /// 根据其他入库订单号查询 
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<string> Get_STK_MISCELLANEOUS(string conStr)
        {
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
                List<object> list = new List<object>();
                var obj = new
                {
                    FormId = "STK_MISCELLANEOUS",
                    FieldKeys = "FBillNo,FQTY,FEntryNote,FCREATEDATE,FMtoNo",//入库单号,入库数量,备注，日期,计划跟踪号
                    FilterString = conStr,
                    OrderString = "",
                    TopRowCount = 100,
                    StartRow = 0,
                    Limit = 0,
                    SubSystemId = ""
                };
                list.Add(obj);
                httpClient.Content = JsonConvert.SerializeObject(list);
                string results = httpClient.AsyncRequest();

                return results;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }

        }

        // <summary>
        /// 根据生产订单编号查询生产用料清单编号20240527z add
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<string> GetPRD_PPBOM(string conStr)
        {
            //FMOBILLNO='GL02MO230100352'
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
                List<object> list = new List<object>();
                var obj = new
                {
                    FormId = "PRD_PPBOM",
                    FieldKeys = "FBILLNO,FMOBILLNO",//用料清单编号，生产订单编号
                    FilterString = conStr,
                    OrderString = "",
                    TopRowCount = 100,
                    StartRow = 0,
                    Limit = 0,
                    SubSystemId = ""
                };
                list.Add(obj);
                httpClient.Content = JsonConvert.SerializeObject(list);
                string results = httpClient.AsyncRequest();

                return results;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }

        }

        /// <summary>
        /// 根据工单号查询金蝶资料
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<PrdPPBom>> SearchPrdPPBomByCondition(string conStr)
        {
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

                List<object> Parameters = new List<object>();
                //string condiStr = "fbillno='" + bill + "'";
                string cols = "fid,fbillno,fmaterialid,fmaterialid.fnumber,fmaterialid.FOLDNUMBER,fmaterialid.fname,fmaterialid.fspecification,fqty," +
                                    "fmobillno,f_abc_text,f_abc_khdm,f_abc_base.fname,fcreatedate,fapprovedate,fmaterialid.flength,f_abc_remarks";

                string counts = "{\"FormId\":\"PRD_PPBOM\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                    "\"FilterString\":\"" + conStr + "\",\"OrderString\":\"\"," + "\"FieldKeys\":\"" + cols + "\"}";
                Parameters.Add(counts);
                httpClient.Content = JsonConvert.SerializeObject(Parameters);
                string results = httpClient.AsyncRequest();
                JArray jarr = JArray.Parse(results);

                List<PrdPPBom> resList = new List<PrdPPBom>();
                int tmpInt = 0;
                decimal tmpDec = 0;
                if (jarr != null && jarr.Count() > 0)
                {
                    foreach (var item in jarr)
                    {
                        PrdPPBom tmpBean = new PrdPPBom();
                        tmpBean.id = item[0] != null && int.TryParse(item[0].ToString(), out tmpInt) ? int.Parse(item[0].ToString()) : 0;
                        tmpBean.bill_no = item[1] != null ? item[1].ToString() : "";
                        tmpBean.material_id = item[2] != null ? item[2].ToString() : "";
                        tmpBean.material_number = item[3] != null ? item[3].ToString() : "";
                        tmpBean.old_number = item[4] != null ? item[4].ToString() : "";
                        tmpBean.material_name = item[5] != null ? item[5].ToString() : "";
                        tmpBean.material_spe = item[6] != null ? item[6].ToString() : "";
                        tmpBean.qty = item[0] != null && decimal.TryParse(item[7].ToString(), out tmpDec) ? decimal.Parse(item[7].ToString()) : 0;
                        tmpBean.mo_bill_no = item[8] != null ? item[8].ToString() : "";
                        tmpBean.mto_no = item[9] != null ? item[9].ToString() : "";
                        tmpBean.client_number = item[10] != null ? item[10].ToString() : "";
                        tmpBean.saler_name = item[11] != null ? item[11].ToString() : "";
                        tmpBean.remark = item[15] != null ? item[15].ToString() : "";
                        tmpBean.create_date = item[12] != null ? item[12].ToString() : "";
                        tmpBean.material_length = item[14] != null ? item[14].ToString() : "";
                        tmpBean.approve_date = item[13] != null ? item[13].ToString() : "";
                        resList.Add(tmpBean);
                    }
                }

                return resList;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }

        }

        /// <summary>
        /// 根据工单号查询金蝶资料
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<PrdInStock>> SearchGoodsInStockForCondition(string condition)
        {
            List<PrdInStock> inList = new List<PrdInStock>();
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();

            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

                List<object> Parameters = new List<object>();
                string condiStr = condition;
                string cols = "fid,fbillno,fmaterialid,fmaterialid.fnumber,fmaterialid.fname,fmaterialid.fspecification," +
                                    "fmobillno,fmtono,frealqty,fmaterialid.flength,fentity_fentryid";

                string counts = "{\"FormId\":\"PRD_INSTOCK\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                    "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"\"," + "\"FieldKeys\":\"" + cols + "\"}";
                Parameters.Add(counts);
                httpClient.Content = JsonConvert.SerializeObject(Parameters);
                string results = httpClient.AsyncRequest();
                JArray tmpArray = JArray.Parse(results);


                if (tmpArray != null && tmpArray.Count > 0)
                {
                    foreach (var item in tmpArray)
                    {
                        if (item[6].ToString().Equals("GL01MO231200366"))
                        {
                            Console.WriteLine("aaa");
                        }
                        decimal tmpDec = 0;
                        PrdInStock tmpBean = new PrdInStock();
                        tmpBean.id = int.Parse(item[0].ToString());
                        tmpBean.bill_no = item[1].ToString();
                        tmpBean.material_id = item[2].ToString();
                        tmpBean.material_number = item[3].ToString();
                        tmpBean.material_name = item[4].ToString();
                        tmpBean.material_spe = item[5].ToString();
                        tmpBean.mo_bill_no = item[6].ToString();
                        tmpBean.mto_no = item[7].ToString();
                        tmpBean.real_qty = decimal.Parse(item[8].ToString());
                        tmpBean.entry_id = int.Parse(item[10].ToString());
                        if (decimal.TryParse(item[9].ToString(), out tmpDec) == true)
                        {
                            tmpBean.goods_length = decimal.Parse(item[9].ToString());
                        }
                        else
                        {
                            List<string> lenList = new List<string>();
                            if (tmpBean.material_spe.Trim().Length > 0)
                            {
                                int tmpInt = 0;
                                char[] chars = tmpBean.material_spe.ToCharArray();
                                if (chars[chars.Count() - 1].ToString().Equals("M") || chars[chars.Count() - 1].ToString().Equals("m"))
                                {
                                    for (int i = chars.Count() - 2; i >= 0; i--)
                                    {
                                        if (chars[i].ToString().Equals(".") || int.TryParse(chars[i].ToString(), out tmpInt) == true)
                                        {
                                            lenList.Add(chars[i].ToString());
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                string lenStr = "";
                                for (int i = lenList.Count - 1; i >= 0; i--)
                                {
                                    lenStr = lenStr + lenList[i].ToString();
                                }
                                if (decimal.TryParse(lenStr, out tmpDec))
                                {
                                    tmpBean.goods_length = decimal.Parse(lenStr);
                                }
                            }
                        }

                        inList.Add(tmpBean);
                    }
                }


                return inList;
            }
            else
            {
                throw new Exception("Login金蝶失败，无法获取资料！");
            }
        }


        


        /// <summary>
        /// 通过生产订单下推成入库单
        /// </summary>
        /// <param name="moNumber">生成订单</param>
        /// <returns></returns>
        public async Task<(bool, string)> PushDownForMoAsync(string moNumber)
        {
            bool isSucc = false;
            string message = "";

            K3CloudLogin k3 = new K3CloudLogin();
            string loginStr = await k3.CheckLogin();
            if (loginStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient client = new Vboot.App.K3CloudDataSend.HttpClient();
                client.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc");

                List<object> parameters = new List<object>();
                string formID = "PRD_MO";
                parameters.Add(formID);

                string jsonStr = "{" +
                                    "\"Ids\" : \"\"," +
                                    "\"Numbers\" : [\"" + moNumber + "\"]," +
                                    "\"EntryIds\" : \"\"," +
                                    "\"RuleId\" : \"\"," +
                                    "\"TargetBillTypeId\" : \"\"," +
                                    "\"TargetOrgId\" : 0," +
                                    "\"TargetFormId\" : \"PRD_INSTOCK\"," +
                                    "\"IsEnableDefaultRule\" : \"true\"," +
                                    "\"IsDraftWhenSaveFail\" : \"false\"," +
                                    "\"CustomParams\" : {}" +
                                "}";
                parameters.Add(jsonStr);
                client.Content = JsonConvert.SerializeObject(parameters);
                string results = client.AsyncRequest();

                JsonNode jNode = JsonNode.Parse(results);
                if (jNode != null)
                {
                    isSucc = jNode["Result"]["ResponseStatus"]["IsSuccess"].GetValue<bool>();
                }

                if (isSucc)
                {
                    message = jNode["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"].GetValue<string>();
                }
                else
                {
                    message = jNode["Result"]["ResponseStatus"]["Errors"][0]["Message"].GetValue<string>();
                }
            }
            else
            {
                message = "登陆金蝶失败！";
            }

            return (isSucc, message);
        }


        /// <summary>
        /// 由生产用料清单下推生成领料单
        /// </summary>
        /// <param name="prodList"></param>
        /// <returns></returns>
        public async Task<(bool, string)> PushPickMtrlForPPBomAsync(string prodNumber)
        {
            bool isSucc = false;
            string message = "";

            K3CloudLogin k3 = new K3CloudLogin();
            string loginStr = await k3.CheckLogin();
            if (loginStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient client = new Vboot.App.K3CloudDataSend.HttpClient();
                client.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc");

                List<object> parameters = new List<object>();
                string formID = "PRD_PPBOM";
                parameters.Add(formID);

                string jsonStr = "{" +
                                    "\"Ids\" : \"\"," +
                                    "\"Numbers\" : [\"" + prodNumber + "\"]," +
                                    "\"EntryIds\" : \"\"," +
                                    "\"RuleId\" : \"\"," +
                                    "\"TargetBillTypeId\" : \"\"," +
                                    "\"TargetOrgId\" : 0," +
                                    "\"TargetFormId\" : \"PRD_PickMtrl\"," +
                                    "\"IsEnableDefaultRule\" : \"true\"," +
                                    "\"IsDraftWhenSaveFail\" : \"false\"," +
                                    "\"CustomParams\" : {}" +
                                "}";
                parameters.Add(jsonStr);
                client.Content = JsonConvert.SerializeObject(parameters);
                string results = client.AsyncRequest();

                JsonNode jNode = JsonNode.Parse(results);
                if (jNode != null)
                {
                    isSucc = jNode["Result"]["ResponseStatus"]["IsSuccess"].GetValue<bool>();
                }

                if (isSucc)
                {
                    message = jNode["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].GetValue<string>() + "|" + 
                                        jNode["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"].GetValue<string>();
                }
                else
                {
                    message = jNode["Result"]["ResponseStatus"]["Errors"][0]["Message"].GetValue<string>();
                }
            }
            else
            {
                message = "登陆金蝶失败！";
            }

            return (isSucc, message);
        }

        /// <summary>
        /// 查询生产订单
        /// </summary>
        /// <param name="moNumber">生产订单号</param>
        /// <returns></returns>
        public async Task<List<MesGLApp.DAL.Kingdee.Mo>> SearchMoForBillNo(string moNumber)
        {
            List<MesGLApp.DAL.Kingdee.Mo> resList = new List<MesGLApp.DAL.Kingdee.Mo>();
            K3CloudLogin k3 = new K3CloudLogin();
            string tmpStr = await k3.CheckLogin();
            if (tmpStr.Equals("SUCCESS"))
            {
                Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
                httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

                List<object> Parameters = new List<object>();
                string condiStr = "fbillno = '" + moNumber + "'";
                string cols = "fid,fbillno,fdate,fmaterialid,fmaterialid.fnumber,fmaterialid.fname,fmaterialid.fspecification,fqty,FTreeEntity_FEntryId,FUnitId";

                string counts = "{\"FormId\":\"PRD_MO\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                    "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"\"," + "\"FieldKeys\":\"" + cols + "\"}";
                Parameters.Add(counts);
                httpClient.Content = JsonConvert.SerializeObject(Parameters);
                string results = httpClient.AsyncRequest();
                JArray tmpArray = JArray.Parse(results);

                int tmpInt = 0;
                decimal tmpDec = 0;
                DateTime tmpDay = new DateTime();
                if (tmpArray.Count > 0)
                {
                    foreach (var item in tmpArray)
                    {
                        MesGLApp.DAL.Kingdee.Mo tmpMo = new MesGLApp.DAL.Kingdee.Mo();
                        tmpMo.id = item[0] != null && int.TryParse(item[0].ToString(), out tmpInt) ? int.Parse(item[0].ToString()) : 0;
                        tmpMo.bill_no = item[1] != null ? item[1].ToString().Trim() : "";
                        tmpMo.fill_date = item[2] != null && DateTime.TryParse(item[2].ToString(), out tmpDay) ? DateTime.Parse(item[2].ToString()).ToString("yyyy-MM-dd") : "";
                        tmpMo.mat_id = item[3] != null && int.TryParse(item[3].ToString(), out tmpInt) ? int.Parse(item[3].ToString()) : 0;
                        tmpMo.goods_info = new Material();
                        tmpMo.goods_info.mat_id = tmpMo.mat_id;
                        tmpMo.goods_info.mat_number = item[4] != null ? item[4].ToString().Trim() : "";
                        tmpMo.goods_info.mat_name = item[5] != null ? item[5].ToString().Trim() : "";
                        tmpMo.goods_info.mat_spe = item[6] != null ? item[6].ToString().Trim() : "";
                        tmpMo.qty = item[7] != null && decimal.TryParse(item[7].ToString(), out tmpDec) ? decimal.Parse(item[7].ToString()) : 0;
                        tmpMo.entry_id = item[8] != null && int.TryParse(item[8].ToString(), out tmpInt) ? tmpInt : 0;
                        tmpMo.unit_id = item[9] != null && int.TryParse(item[9].ToString(), out tmpInt) ? tmpInt : 0;
                        resList.Add(tmpMo);
                    }
                }
            }
            return resList;
        }


        /// <summary>
        /// 更新生产入库单的数量
        /// </summary>
        /// <param name="inStockID">入库单主表的ID</param>
        /// <param name="entryID">入库单明细的ID</param>
        /// <param name="qty">实际入库数量</param>
        /// <param name="isComp">是否已经完结</param>
        /// <param name="remark">备注</param>
        /// <param name="prodLine">生产线，分一线、二线、小单组</param>
        /// <returns></returns>
        public async Task<(bool, string)> UpdateInStockAfterPushAsync(int inStockID, int entryID, decimal qty, bool isComp, string remark, string prodLine)
        {
            bool isSucc = false;
            string message = "";

            K3CloudLogin k3 = new K3CloudLogin();
            string loginStr = await k3.CheckLogin();
            if (loginStr.Equals("SUCCESS"))
            {
                //调用保存接口
                Vboot.App.K3CloudDataSend.HttpClient client = new Vboot.App.K3CloudDataSend.HttpClient();
                client.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");

                List<object> parameters = new List<object>();
                string formID = "PRD_INSTOCK";
                parameters.Add(formID);

                string jsonStr = "{" +
                                    "\"NeedUpDateFields\" : []," +
                                    "\"NeedReturnFields\" : []," +
                                    "\"IsDeleteEntry\" : \"false\"," +
                                    "\"SubSystemId\" : \"\"," +
                                    "\"IsVerifyBaseDataField\" : \"false\"," +
                                    "\"IsEntryBatchFill\" : \"true\"," +
                                    "\"ValidateFlag\" : \"true\"," +
                                    "\"NumberSearch\" : \"true\"," +
                                    "\"IsAutoAdjustField\" : \"false\"," +
                                    "\"InterationFlags\" : \"\"," +
                                    "\"IgnoreInterationFlag\" : \"\"," +
                                    "\"Model\" : {" +
                                        "\"FID\" : " + inStockID.ToString() + "," +
                                        "\"FStockId\" : {" +
                                            "\"FNUMBER\" : \"FG101\"" +     //FG101 成品仓代号
                                        "}," +
                                        "\"FDescription\" : \"" + remark + "\"," +
                                        "\"F_ABC_Base\" : {" +
                                            "\"FNUMBER\" : \"GLD0005\"" +   //GLD0005  线一生产部
                                        "}," +
                                        "\"FCreatorId\" : {" +
                                            "\"FUSERID\" : 457188" +
                                        "}," +
                                        "\"ModifierId\" : {" +
                                            "\"FUSERID\" : 457188" +
                                        "}," +
                                        "\"FEntity\" : [{" +
                                            "\"FEntryID\" : " + entryID.ToString() + "," +
                                            "\"FRealQty\" : " + qty.ToString() + "," +
                                            "\"FBASEREALQTY\" : " + qty.ToString() + "," +
                                            "\"FSTOCKREALQTY\" : " + qty.ToString() + "," +
                                            "\"FSECREALQTY\" : " + qty.ToString() + "," +
                                            "\"FIsFinished\" : \"" + isComp.ToString() + "\"," +
                                            "\"F_ABC_Text\" : \"" + prodLine + "\"," +
                                            "\"FLot\" : {" +
                                                "\"FNumber\" : \"GL01PH01\"" +   //GL01PH01 批号：GL01PH01
                                            "}" +
                                        "}]" +
                                    "}" +
                                 "}";
                parameters.Add(jsonStr);
                client.Content = JsonConvert.SerializeObject(parameters);
                string results = client.AsyncRequest();
                JsonNode jNode = JsonNode.Parse(results);
                if (jNode != null)
                {
                    isSucc = jNode["Result"]["ResponseStatus"]["IsSuccess"].GetValue<bool>();
                }

                if (isSucc)
                {
                    message = jNode["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"].GetValue<string>();
                }
                else
                {
                    message = jNode["Result"]["ResponseStatus"]["Errors"][0]["Message"].GetValue<string>();
                }
            }
            else 
            {
                message = "Login金蝶失败，无法获取资料！";
            }

            return (isSucc, message);
        }


        /// <summary>
        /// 提交入库单
        /// </summary>
        /// <param name="inStockNo">入库单号</param>
        /// <returns></returns>
        public async Task<(bool, string)> SubmitInStockAsync(string inStockNo)
        {
            bool isSucc = false;
            string message = "";

            K3CloudLogin k3 = new K3CloudLogin();
            string loginStr = await k3.CheckLogin();
            if (loginStr.Equals("SUCCESS"))
            {
                HttpClient client = new HttpClient();
                client.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");

                List<object> parameters = new List<object>();
                string formID = "PRD_INSTOCK";
                parameters.Add(formID);

                string jsonStr = "{" +
                                    "\"CreateOrgId\" : 0," +
                                    "\"Numbers\" : [\"" + inStockNo + "\"]," +
                                    "\"Ids\" : \"\"," +
                                    "\"SelectedPostId\" : 0," +
                                    "\"NetworkCtrl\" : \"\"," +
                                    "\"IgnoreInterationFlag\" : \"\"" +
                                   "}";
                parameters.Add(jsonStr);
                client.Content = JsonConvert.SerializeObject(parameters);
                string results = client.AsyncRequest();
                JsonNode jNode = JsonNode.Parse(results);
                if (jNode != null)
                {
                    isSucc = jNode["Result"]["ResponseStatus"]["IsSuccess"].GetValue<bool>();
                }

                if (isSucc)
                {
                    message = jNode["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"].GetValue<string>();
                }
                else
                {
                    message = jNode["Result"]["ResponseStatus"]["Errors"][0]["Message"].GetValue<string>();
                }
            }
            else
            {
                message = "Login金蝶失败，无法获取资料！";
            }
            return (isSucc, message);
        }


        /// <summary>
        /// 更新生产订单明细中的MES流程完成状态
        /// </summary>
        /// <param name="moBillNo">生产订单号，即MO单号</param>
        /// <param name="goodsNumber">主件品号</param>
        /// <param name="mesStatus">MES完成状态</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> UpdateMoentryMesStatus(string moBillNo, string goodsNumber, int mesStatus)
        {
            //根据MO单号、主件品号，从金蝶系统中取得MO单的明细资料
            List<DAL.Kingdee.Mo> moList = await this.SearchMoForBillNo(moBillNo);
            if (moList.Count > 0)
            {
                //登陆验证金蝶webapi，准备调用保存接口
                K3CloudLogin k3 = new K3CloudLogin();
                string loginStr = await k3.CheckLogin();
                string models = "";

                if (loginStr.Equals("SUCCESS"))
                {
                    //调用保存接口
                    Vboot.App.K3CloudDataSend.HttpClient client = new Vboot.App.K3CloudDataSend.HttpClient();
                    client.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");


                    //设定保存的表单ID
                    List<object> parameters = new List<object>();
                    string formid = "PRD_MO";
                    parameters.Add(formid);

                    string entryStr = "";
                    foreach (var item in moList)
                    {
                        entryStr = entryStr + "{" +
                                        "\"FEntryID\" : " + item.entry_id.ToString() + "," +
                                        "\"F_MES_ISCOMP\" : " + mesStatus.ToString() +
                                        "},";
                    }
                    entryStr = entryStr.Substring(0, entryStr.Length - 1);

                    //设定保存的实体
                    models = "{" +
                                "\"FID\" : " + moList[0].id.ToString() + "," +
                                "\"FTreeEntity\" : [" + entryStr + "] " +
                             "}";

                    //设定保存Data
                    string jsonStr = "{" +
                                            "\"NumberSearch\" : \"true\"," +
                                            "\"ValidateFlag\" : \"true\"," +
                                            "\"IsDeleteEntry\" : \"false\"," +
                                            "\"IsEntryBatchFill\" : \"true\"," +
                                            "\"NeedUpDateFields\" : []," +
                                            "\"NeedReturnFields\" : []," +
                                            "\"SubSystemId\" : \"\"," +
                                            "\"InterationFlags\" : \"\"," +
                                            "\"Model\" : " + models + "," +
                                            "\"BatchCount\" : 0," +
                                            "\"IsVerifyBaseDataField\" : \"false\"," +
                                            "\"IsAutoAdjustField\" : \"false\"," +
                                            "\"IgnoreInterationFlag\" : \"false\"" +
                                      "}";

                    //执行保存，获取报文
                    parameters.Add(jsonStr);
                    client.Content = JsonConvert.SerializeObject(parameters);
                    string results = client.AsyncRequest();
                    JObject jsonResponse = JObject.Parse(results);

                    bool isSuccess = (bool)jsonResponse["Result"]["ResponseStatus"]["IsSuccess"];
                    return isSuccess;
                }
                else
                {
                    throw new Exception("金蝶Webapi登陆失败，无法修改生产订单的MES完成状态！");
                }
            }
            else
            {
                return false;
            }
        }

        public async Task<(bool, string)> InitInStockForMo(string moNumber, string mtoNumber, decimal scanQty, string remark, string prodLine)
        {
            bool isSucc = false;
            string message = "";

            string mes1 = "生产订单查询：✘" + "\r\n";
            string mes2 = "下推：✘" + "\r\n";
            string mes3 = "修改：✘" + "\r\n";
            string mes4 = "提交：✘" + "\r\n";

            List<MesGLApp.DAL.Kingdee.Mo> moList = await this.SearchMoForBillNo(moNumber);
            if (moList != null && moList.Count > 0)
            {
                mes1 = "生产订单查询：✓" + "\r\n";
                bool tmpSucc = false;
                string tmpMessage = "";

                //先由生产订单下推成生产入库单
                (tmpSucc, tmpMessage) = await this.PushDownForMoAsync(moNumber);
                if (tmpSucc)
                {
                    //下推成功后，下推返回的是入库单单号
                    mes2 = "下推：✓，单号：" + tmpMessage + "\r\n";
                    string inStockNo = tmpMessage;

                    //下推成功后，根据生产订单找到现在已有的入库单资料，并取得刚下推生成的入库单资料
                    List<PrdInStock> inStockList = await this.SearchGoodsInStockForCondition("fmobillno = '" + moNumber + "'");
                    List<PrdInStock> newList = await this.SearchGoodsInStockForCondition("fbillno = '" + inStockNo + "'");

                    decimal totalQty = 0;           //生产订单数量
                    decimal clearQty = 0;           //已入库数量
                    bool isComp = false;            //生产订单是否完结
                    if (newList != null && newList.Count > 0)
                    {
                        if (moList != null && moList.Count > 0)
                        {
                            //判断这次入库后，生产订单是否完结。
                            totalQty = moList[0].qty;
                            if (inStockList != null && inStockList.Count > 0)
                            {
                                foreach (var item in inStockList)
                                {
                                    if (item.mo_bill_no.Equals(moList[0].bill_no) && item.material_number.Equals(moList[0].goods_info.mat_number) && item.bill_no.Equals(newList[0].bill_no) == false)
                                    {
                                        clearQty = clearQty + item.real_qty;
                                    }
                                }
                            }
                        }

                        if (clearQty + scanQty >= totalQty)
                        {
                            isComp = true;
                        }

                        tmpSucc = false;
                        tmpMessage = "";
                        (tmpSucc, tmpMessage) = await this.UpdateInStockAfterPushAsync(newList[0].id, newList[0].entry_id, scanQty, isComp, remark, prodLine);
                        if (tmpSucc)
                        {
                            mes3 = "修改：✓" + "\r\n";
                            tmpSucc = false;
                            tmpMessage = "";
                            (tmpSucc, tmpMessage) = await this.SubmitInStockAsync(newList[0].bill_no);
                            if (tmpSucc)
                            {
                                isSucc = true;
                                mes4 = "提交：✓" + "\r\n";
                            }
                            else
                            {
                                isSucc = false;
                                mes4 = "提交：✘" + "\r\n";
                                message = tmpMessage;
                            }
                        }
                        else
                        {
                            isSucc = false;
                            mes3 = "修改：✘" + "\r\n";
                            message = tmpMessage;
                        }
                    }
                }
                else
                {
                    isSucc = false;
                    mes2 = "下推：✘" + "\r\n";
                    message = tmpMessage;
                }
            }
            else
            {
                isSucc = false;
                mes1 = "生产订单查询：✘" + "\r\n";
            }


            message = mes1 + mes2 + mes3 + mes4 + message;
            return (isSucc, message);
        }

        /// <summary>
        /// 获取人员组织ID
        /// </summary>
        /// <param name="staffnumber"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public JArray GetKingDeeOrganizationID(string staffnumber)
        {
            List<object> Parameters = new List<object>();

            K3CloudLogin k3CloudLogin = new K3CloudLogin();
            k3CloudLogin.CheckLogin();

            Vboot.App.K3CloudDataSend.HttpClient httpClient = new Vboot.App.K3CloudDataSend.HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");

            string condiStr = $"fnumber = '{staffnumber}'";

            string cols = "FOrgID";

            string data = "{\"FormId\":\"ORG_Organizations\",\"TopRowCount\":0,\"Limit\":0,\"StartRow\":0," +
                                  "\"FilterString\":\"" + condiStr + "\",\"OrderString\":\"\"," + "\"FieldKeys\":\"" + cols + "\"}";
            Parameters.Add(data);
            httpClient.Content = JsonConvert.SerializeObject(Parameters);
            var results = httpClient.AsyncRequest().ToArray();

            string str = "";

            foreach (var item in results)
            {
                str += item;
            }

            JArray jArray = JArray.Parse(str);

            if (!results.ToString().Contains("\"Errors\""))
            {
                return jArray;
            }
            else
            {
                throw new Exception("无法获取金蝶数据！" + "\r\n" + jArray[0].ToString());
            }
        }
    }
}
